<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form ref="filterForm" :model="filterForm" :inline="true" label-position="left" label-width="100px">
        <el-form-item label="关键字" prop="keyword">
          <el-input v-model="filterForm.keyword" placeholder="员工ID/姓名/联系电话" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
        </el-form-item>
        <el-form-item label="部门" prop="departmentID">
          <el-select v-model="filterForm.departmentID" placeholder="请选择">
            <el-option
              v-for="item in departmentOptions"
              :key="item.ID"
              :label="item.title"
              :value="item.ID"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="职位" prop="departmentID">
          <el-select v-model="filterForm.positionID" placeholder="请选择">
            <el-option
              v-for="item in positionOptions"
              :key="item.ID"
              :label="item.title"
              :value="item.ID"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="入职时间" prop="inductionTime">
          <el-date-picker 
            v-model="filterForm.tradeTime"
            type="datetimerange"
            format="yyyy-MM-dd HH:MM:SS"
            value-format="yyyy-MM-dd HH:MM:SS"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
            <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
              搜索
            </el-button>
            <el-button v-waves class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">
              新建
            </el-button>
            <el-button class="filter-item" style="margin-left: 10px;" type="primary" @click="handleExport">
              导出
            </el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="55"
      />
      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="140" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.sn }}</span>
        </template>
      </el-table-column>
      <el-table-column label="头像" max-width="80px">
        <template slot-scope="{row}">
          <span ><el-avatar  :src="row.avatar"></el-avatar></span>
        </template>
      </el-table-column>
      <el-table-column label="用户名" min-width="150px">
        <template slot-scope="{row}">
          <span >{{ row.username }}</span>
        </template>
      </el-table-column>
      <el-table-column label="姓名" min-width="150px">
        <template slot-scope="{row}">
          <span class="link-type" @click="handleShow(row)">{{ row.fullname }}</span>
        </template>
      </el-table-column>
      <el-table-column label="电话" min-width="150px">
        <template slot-scope="{row}">
          <span class="link-type" @click="handleShow(row)">{{ row.telephone }}</span>
        </template>
      </el-table-column>
      <el-table-column label="隶属组织" min-width="150px">
        <template slot-scope="{row}">
          <div>部门：{{ row.department.title }}</div>
          <div>职位：{{ row.position.title }}</div>
        </template>
      </el-table-column>
      <el-table-column label="管理范围" min-width="150px">
        <template slot-scope="{row}">
          <div>{{ row.scope.label }}</div>
        </template>
      </el-table-column>
      <el-table-column label="状态" class-name="status-col" width="100">
        <template slot-scope="{row}">
          <el-tag :type="row.status">
            {{ row.status.label }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="修改时间" class-name="status-col" width="180">
        <template slot-scope="{row}">
            {{ row.updatedAt }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button v-if="row.status.value == 6" size="mini" @click="handleModifyStatus(row,5)">
            禁用
          </el-button>
          <el-button v-if="row.status.value == 1 || row.status.value == 5 " size="mini" @click="handleModifyStatus(row,6)">
            启用
          </el-button>
          <el-button v-if="row.status.value == 1 || row.status.value == 5" size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="filterForm.start" :limit.sync="filterForm.perpage" @pagination="getList" />

  </div>
</template>

<script>
import { getEmployeeList,  removeEmployeeByID, changeEmployeeStatusByID } from '@/api/mechanism/employee'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

export default {
  name: 'employeeAdmin',
  components: { Pagination },
  directives: { waves },
  filters: {
  },
  data() {
    return {
      selectedIDs:[],
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      positionOptions:[],
      departmentOptions:[],
      filterForm: {
        start: 1,
        perpage: 10,
        title: undefined,
        sort: '+id'
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      getEmployeeList(this.filterForm).then(response => {
        this.list = response.data.list
        this.total = response.data.total

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleSelectionChange(item) {
      this.selectedIDs = [];
      item.forEach((row)=>{
        this.selectedIDs.push(row['ID'])
      });
    },
    handleShow:function(item){
      this.$router.push({ path: 'employee-detail', query: { 'employeeID': item.ID }})
    },
    handleCreate:function(){
      this.$router.push({ path: 'employee-add'})
    },
    handleUpdate:function(item){
      this.$router.push({ path: 'employee-add', query: { 'employeeID': item.ID }})
    },
    handleFilter() {
      this.filterForm.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      changeEmployeeStatusByID({
        "employeeID":row.ID,
        "status":status
      }).then((response) => {
          if (response.status === 200) {
            this.$message({
              message: '操作Success',
              type: 'success'
            })
            this.getList()
          } else {
            this.$message({
              message: response.msg,
              type: 'error'
            })
          }
      })
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.filterForm.sort = '+id'
      } else {
        this.filterForm.sort = '-id'
      }
      this.handleFilter()
    },
    handleBatchDelete(row, index) {
      if(this.selectedIDs.length < 1){
          this.$message({
            message: '请选择要操作的数据',
            type: 'error'
          })
          return false;
      }
      let _formData = {
        "employeeID":this.selectedIDs
      }
      this.selectedIDs = [];
      removeEmployeeByID(_formData).then((response) => {
          if (response.status === 200) {
            this.$message({
              message: '操作Success',
              type: 'success'
            })
            this.getList()
          } else {
            this.$message({
              message: response.msg,
              type: 'error'
            })
          }
      })
    },
    handleDelete(row, index) {
      let _formData = {
        "employeeID":row.ID
      }
      this.$confirm('确实要执行此操作?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
          removeEmployeeByID(_formData).then((response) => {
              if (response.status === 200) {
                this.$message({
                  message: '操作Success',
                  type: 'success'
                })
                this.getList()
              } else {
                this.$message({
                  message: response.msg,
                  type: 'error'
                })
              }
          })
      }).catch(() => {
      })
    },
    handleRecall(row, index) {
      this.getList()
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.filterForm.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
